/**
 * 分类右键菜单组件
 */

import React, { useEffect, useRef } from 'react';
import { Plus, Edit, Trash2 } from 'lucide-react';
import type { DocumentCategory } from '@/types/document';

interface MenuItem {
  label: string;
  icon: React.ComponentType<{ className?: string }>;
  action: string;
  danger?: boolean;
  disabled?: boolean;
}

interface CategoryContextMenuProps {
  isOpen: boolean;
  position: { x: number; y: number };
  category: DocumentCategory | null;
  onClose: () => void;
  onAction: (action: string, category: DocumentCategory) => void;
}

const CategoryContextMenu: React.FC<CategoryContextMenuProps> = ({
  isOpen,
  position,
  category,
  onClose,
  onAction
}) => {
  const menuRef = useRef<HTMLDivElement>(null);

  // 点击外部关闭菜单
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (menuRef.current && !menuRef.current.contains(event.target as Node)) {
        onClose();
      }
    };

    if (isOpen) {
      document.addEventListener('mousedown', handleClickOutside);
      return () => document.removeEventListener('mousedown', handleClickOutside);
    }
  }, [isOpen, onClose]);

  // ESC键关闭菜单
  useEffect(() => {
    const handleKeyDown = (event: KeyboardEvent) => {
      if (event.key === 'Escape') {
        onClose();
      }
    };

    if (isOpen) {
      document.addEventListener('keydown', handleKeyDown);
      return () => document.removeEventListener('keydown', handleKeyDown);
    }
  }, [isOpen, onClose]);

  if (!isOpen || !category) return null;

  const menuItems: MenuItem[] = [
    {
      label: '新建子分类',
      icon: Plus,
      action: 'create-child',
      disabled: false
    },
    {
      label: '编辑分类',
      icon: Edit,
      action: 'edit',
      disabled: false
    },
    {
      label: '删除分类',
      icon: Trash2,
      action: 'delete',
      danger: true,
      disabled: category.is_system // 系统分类不能删除
    }
  ];

  const handleItemClick = (item: MenuItem) => {
    if (item.disabled) return;
    onAction(item.action, category);
    onClose();
  };

  return (
    <div
      ref={menuRef}
      className="fixed bg-white border border-zinc-200 rounded-lg shadow-lg py-1 z-50 min-w-[140px]"
      style={{
        left: position.x,
        top: position.y,
      }}
    >
      {menuItems.map((item, index) => {
        const Icon = item.icon;
        return (
          <button
            key={index}
            onClick={() => handleItemClick(item)}
            disabled={item.disabled}
            className={`w-full flex items-center px-3 py-2 text-sm text-left transition-colors ${
              item.disabled
                ? 'text-zinc-400 cursor-not-allowed'
                : item.danger
                ? 'text-red-600 hover:bg-red-50'
                : 'text-zinc-700 hover:bg-zinc-50'
            }`}
          >
            <Icon className="w-4 h-4 mr-2" />
            {item.label}
          </button>
        );
      })}
    </div>
  );
};

export default CategoryContextMenu;
